package com.xiaoxie.common.config;

import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.core5.util.Timeout;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Configuration
public class HttpClientConfig {

    @Value("${http.client.connect-timeout:5000}")   // 连接超时时间，单位毫秒
    private int connectionTimeout;

    @Value("${http.client.socket-timeout:10000}")   // 读取超时时间，单位毫秒
    private int socketTimeout;

    @Value("${http.client.max-connections:200}")    // 最大连接数
    private int maxConnections;

    @Value("${http.client.max-pre-route:50}")       // 最大并发连接数
    private int maxPreRoute;

    @Bean
    public CloseableHttpClient httpClient() {
        PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
                .setMaxConnTotal(maxConnections)
                .setMaxConnPerRoute(maxPreRoute)
                .build();

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(Timeout.of(Duration.ofMillis(connectionTimeout)))
                .setResponseTimeout(Timeout.of(Duration.ofMillis(socketTimeout)))
                .build();

        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
    }
}
